package org.jeecgframework.web.service.impl;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.collections.map.HashedMap;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.service.ZyEquipmentChangeServiceI;
import org.jeecgframework.web.service.ZyWorkFlowService;
import org.jeecgframework.web.system.pojo.base.CbsAppMessageEntity;
import org.jeecgframework.web.system.pojo.base.TSBaseUser;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSRoleUser;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.pojo.base.ZyContactsEntity;
import org.jeecgframework.web.system.pojo.base.ZyEmailEntity;
import org.jeecgframework.web.system.pojo.base.ZyEngineerEntity;
import org.jeecgframework.web.system.pojo.base.ZyEquipmentChangeEntity;
import org.jeecgframework.web.system.pojo.base.ZyInspectionPlanEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.SendMailUtil;
import org.jeecgframework.web.util.SendMessage;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.io.Serializable;

import javax.servlet.http.HttpServletRequest;

@Service("zyEquipmentChangeService")
@Transactional
public class ZyEquipmentChangeServiceImpl extends CommonServiceImpl implements ZyEquipmentChangeServiceI {

	@Autowired
	private ZyWorkFlowService zyWorkFlowService;
	@Autowired
	private ZyCommonService zyCommonService;
	@Autowired
	private SystemService systemService;
	
 	public <T> void delete(T entity) {
 		super.delete(entity);
 		//执行删除操作配置的sql增强
		this.doDelSql((ZyEquipmentChangeEntity)entity);
 	}
 	
 	public <T> Serializable save(T entity) {
 		Serializable t = super.save(entity);
 		//执行新增操作配置的sql增强
 		this.doAddSql((ZyEquipmentChangeEntity)entity);
 		return t;
 	}
 	
 	public <T> void saveOrUpdate(T entity) {
 		super.saveOrUpdate(entity);
 		//执行更新操作配置的sql增强
 		this.doUpdateSql((ZyEquipmentChangeEntity)entity);
 	}
 	
 	/**
	 * 默认按钮-sql增强-新增操作
	 * @param id
	 * @return
	 */
 	public boolean doAddSql(ZyEquipmentChangeEntity t){
	 	return true;
 	}
 	/**
	 * 默认按钮-sql增强-更新操作
	 * @param id
	 * @return
	 */
 	public boolean doUpdateSql(ZyEquipmentChangeEntity t){
	 	return true;
 	}
 	/**
	 * 默认按钮-sql增强-删除操作
	 * @param id
	 * @return
	 */
 	public boolean doDelSql(ZyEquipmentChangeEntity t){
	 	return true;
 	}
 	
 	/**
	 * 替换sql中的变量
	 * @param sql
	 * @return
	 */
 	public String replaceVal(String sql,ZyEquipmentChangeEntity t){
 		sql  = sql.replace("#{id}",String.valueOf(t.getId()));
 		sql  = sql.replace("#{change_id}",String.valueOf(t.getChangeId()));
 		sql  = sql.replace("#{queipment_sapre_id}",String.valueOf(t.getEquipmentSpareSn()));
 		sql  = sql.replace("#{plan_id}",String.valueOf(t.getPlanId()));
 		sql  = sql.replace("#{change_type}",String.valueOf(t.getChangeType()));
 		sql  = sql.replace("#{request_time}",String.valueOf(t.getRequestTime()));
 		sql  = sql.replace("#{approval_time}",String.valueOf(t.getApprovalTime()));
 		sql  = sql.replace("#{approval_state}",String.valueOf(t.getApprovalState()));
 		sql  = sql.replace("#{approval_remark}",String.valueOf(t.getApprovalRemark()));
 		sql  = sql.replace("#{UUID}",UUID.randomUUID().toString());
 		return sql;
 	}
 	
 	
	public void generateChangeReqId(ZyEquipmentChangeEntity zyEquipmentChange) {
		Calendar calendar = Calendar.getInstance();
		StringBuffer sb = new StringBuffer();
		//PMC + 年份 + 五位数字（默认从1增长）
		String year = String.valueOf(calendar.get(Calendar.YEAR));
		sb.append("PMC").append(year.substring(2));
		Map<String, Object> rsMap = super.findOneForJdbc("SELECT change_id FROM zy_equipment_change ORDER BY change_id DESC LIMIT 0,1");
		String partThree;
		if(rsMap != null){
			if(StringUtil.isNotEmpty(rsMap.get("change_id"))){
				String currMaxId = rsMap.get("change_id").toString().substring(5);
				Long maxIdLong = Long.valueOf(currMaxId);
				Long currMaxIdLong =  maxIdLong + 1;
				if(currMaxIdLong >= 1 && currMaxIdLong <= 9){
					sb.append("00000").append(currMaxIdLong);
				}else if(currMaxIdLong >= 10 && currMaxIdLong <= 99){
					sb.append("0000").append(currMaxIdLong);
				}else if(currMaxIdLong >= 100 && currMaxIdLong <= 999){
					sb.append("000").append(currMaxIdLong);
				}else if(currMaxIdLong >= 1000 && currMaxIdLong <= 9999){
					sb.append("00").append(currMaxIdLong);
				}else if(currMaxIdLong >= 10000 && currMaxIdLong <= 99999){
					sb.append("0").append(currMaxIdLong);
				}else if(currMaxIdLong >= 10000 && currMaxIdLong <= 999999){
					sb.append(currMaxIdLong);
				}
			}else{
				//初始化
				partThree = "000001";
				sb.append(partThree);
			}
		}else{
			//初始化
			partThree = "000001";
			sb.append(partThree);
		}
		zyEquipmentChange.setChangeId(sb.toString());
	}

//	@Override
	public String doStartProcess(ZyEquipmentChangeEntity zyEquipmentChange,String company) {
		try {
			/**原本这里查询的是当前登录用户的所属组织机构，因为webService中调用时没有session 查询不到用户，所以修改此处 --- begin ---*/
			if(null == company){
				TSUser tsUser = ResourceUtil.getSessionUserName();
				if(null != tsUser){
					company = null != tsUser.getCurrentDepart() ? tsUser.getCurrentDepart().getOrgCode() : null;
				}
			}
			/**原本这里查询的是当前登录用户的所属组织机构，因为webService中调用时没有session 查询不到用户，所以修改此处 --- end ---*/
			zyEquipmentChange.setInspectionCompany(company);
			zyEquipmentChange.setRequestTime(new Date());
			zyEquipmentChange.setApprovalState(StaticValue.DIC_EQ_REQ_STATE_NOT_APPROVAL);
			generateChangeReqId(zyEquipmentChange);
			this.save(zyEquipmentChange);
			ProcessInstance processInstance = zyWorkFlowService.startOnlineProcess(StaticValue.P_FORM_ZY_EQUIPMENT_CHANGE, zyEquipmentChange.getId().toString(),new HashMap<String, Object>());
			zyEquipmentChange.setProcessInstanceId(processInstance.getId());
			this.saveOrUpdate(zyEquipmentChange);
			//发送邮件
			List<Map<String, Object>> userMapList = zyCommonService.queryUserNamesListByOrgCodeAndRoleCode(StaticValue.ORG_CODE_BARCO,StaticValue.RULE_CODE_BARCO_SERVER_DIRECTOR);
			if(userMapList != null && userMapList.size() > 0){
				TSUser tsUser = super.get(TSUser.class, userMapList.get(0).get("id").toString());
				if(tsUser.getEmail() != null){
					ZyEmailEntity eMail = new ZyEmailEntity();
					eMail.setEmailSubject("巴可巡检设备变更申请审批通知");	
					eMail.setEmailReceiver(tsUser.getEmail());
					Map<String, Object> paraMap = new HashMap<String, Object>();
					paraMap.put("barcoServerDirectorName", tsUser.getRealName());
					paraMap.put("changeId", zyEquipmentChange.getChangeId());
					paraMap.put("url", StaticValue.HTTP_HEADER);
					SendMailUtil.sendFtlMail(eMail, "mail_esChangeSendToBarco.ftl", paraMap,systemService);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return zyEquipmentChange.getId();
	}

	@Override
	public void doApproval(HttpServletRequest request) {
		String changeId = oConvertUtils.getString(request.getParameter("id"));
		String approvalFlag = oConvertUtils.getString(request.getParameter("approvalFlag"));
		String approvalRemark = oConvertUtils.getString(request.getParameter("approvalRemark"));
		ZyEquipmentChangeEntity zyEquipmentChange = super.get(ZyEquipmentChangeEntity.class, changeId);
		String approvalResult = "";
		if(approvalFlag.equals("true")){
			approvalResult = "审批通过";
			zyEquipmentChange.setApprovalState(StaticValue.DIC_EQ_REQ_STATE_PASS);
		}else{
			zyEquipmentChange.setApprovalState(StaticValue.DIC_EQ_REQ_STATE_NOT_PASS);
			approvalResult = "审批不通过";
		}
		zyEquipmentChange.setApprovalRemark(approvalRemark);
		zyEquipmentChange.setApprovalTime(new Date());
		this.saveOrUpdate(zyEquipmentChange);
		zyWorkFlowService.processComplete("1", zyEquipmentChange.getProcessInstanceId(), "", "", "");
		//发送APP 消息
		TSBaseUser baseUser = super.findUniqueByProperty(TSBaseUser.class, "userName", zyEquipmentChange.getCreateBy());
		if(null != baseUser){
			TSUser user = ResourceUtil.getSessionUserName();
			CbsAppMessageEntity appMessage = new CbsAppMessageEntity();
			String content = "您的巡检设备变更申请" + zyEquipmentChange.getChangeId() + approvalResult + "，可在“我的申请”中查看详情。";
			appMessage.setContent(content);
			appMessage.setSender(user.getId());
			appMessage.setReciver(baseUser.getId());
			appMessage.setState(StaticValue.DIC_APP_MESSAGE_STATE_UNREAD);
			systemService.save(appMessage);
			systemService.addLog("新增APP消息,接受方:" + baseUser.getId() + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);
		}
		//发送短信
		try {
			String createBy = zyEquipmentChange.getCreateBy();
			StringBuffer sql = new StringBuffer();
			sql.append(" SELECT ");
			sql.append(" ct.`name`, ");
			sql.append(" ct.cellphone1, ");
			sql.append(" ct.cellphone2 ");
			sql.append(" FROM ");
			sql.append(" zy_contacts ct ");
			sql.append(" LEFT JOIN t_s_base_user bu ON bu.id = ct.base_id ");
			sql.append(" LEFT JOIN zy_equipment_change ec ON ec.create_by = bu.username ");
			sql.append(" WHERE ");
			sql.append(" ec.create_by = '").append(createBy).append("' ");
			List<Map<String, Object>> ctMapList = systemService.findForJdbc(sql.toString());
			if(ctMapList != null && ctMapList.size() > 0){//查到工程师就发工程师的电话,查到联系人就发联系人的电话
				String applicant = ctMapList.get(0).get("name").toString();
				String cellPhone = "";
				if(!ctMapList.get(0).get("cellphone1").toString().equals("")){
					cellPhone =  ctMapList.get(0).get("cellphone1").toString();
				}else if(!ctMapList.get(0).get("cellphone2").toString().equals("")){
					cellPhone = ctMapList.get(0).get("cellphone2").toString();
				}
				if(!cellPhone.equals("")){
					Map<String, Object> paraMap = new HashMap<String, Object>();
					paraMap.put("applicant", applicant);
					paraMap.put("changeId", zyEquipmentChange.getChangeId());
					paraMap.put("applyResult", approvalResult);
					SendMessage.sendSMSFTL(cellPhone,"message_esChangeSendToApplicant.ftl", paraMap,systemService);
					systemService.addLog("发送短信,接受方:" + cellPhone + ",内容:" + approvalResult, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);
				}
			}
			sql = new StringBuffer();
			sql.append(" SELECT ");
			sql.append(" eg.`name`, ");
			sql.append(" eg.cellphone ");
			sql.append(" FROM ");
			sql.append(" zy_engineer eg ");
			sql.append(" LEFT JOIN t_s_base_user bu ON bu.id = eg.ts_base_user_id ");
			sql.append(" LEFT JOIN zy_equipment_change ec ON ec.create_by = bu.username ");
			sql.append(" WHERE ");
			sql.append(" ec.create_by = '").append(createBy).append("' ");
			List<Map<String, Object>> egMapList = systemService.findForJdbc(sql.toString());
			if(egMapList != null && egMapList.size() > 0){
				String applicant = egMapList.get(0).get("name").toString();
				String cellPhone = egMapList.get(0).get("cellphone").toString();
				if(!cellPhone.equals("")){
					Map<String, Object> paraMap = new HashMap<String, Object>();
					paraMap.put("applicant", applicant);
					paraMap.put("changeId", zyEquipmentChange.getChangeId());
					paraMap.put("applyResult", approvalResult);
					SendMessage.sendSMSFTL(cellPhone,"message_esChangeSendToApplicant.ftl", paraMap,systemService);
					systemService.addLog("发送短信,接受方:" + cellPhone + ",内容:" + approvalResult, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public List<Map<String, Object>> queryAppEgEsChangeListData() {
		List<Map<String, Object>> mapList = new ArrayList<Map<String,Object>>();
		TSUser user = ResourceUtil.getSessionUserName();
		List<TSRoleUser> roleUsers = systemService.findByProperty(TSRoleUser.class, "TSUser.id", user.getId());
		for (TSRoleUser tsRoleUser : roleUsers) {
			if(tsRoleUser.getTSRole().getRoleCode().equals(StaticValue.RULE_CODE_THIRDPARTY_HEADER)){
				//如果是第三方负责人 ，查询自己所属机构下的所有人提交的申请
				TSDepart depart = user.getCurrentDepart();
				if(null != depart){
					depart = zyCommonService.getUserRootTsDepartCode(depart);
					StringBuffer sql = new StringBuffer();
					sql.append(" SELECT ");
					sql.append(" 	DISTINCT ec.id, ec.change_id AS changeId, DATE_FORMAT(ec.create_date,'%Y-%m-%d') AS createDate, tp.typename AS changeTypeVal, ");
					sql.append("	ec.create_name AS createName, IFNULL(ec.plan_id,'无') AS planId, ec.equipment_spare_sn, cm.name AS cienmaNameVal, tp1.typename AS reasonTypeVal, ");
					sql.append("	ec.req_other_reason ,ec.approval_state , tp2.typename AS approvalStateVal, ec.approval_remark AS approvalRemark ");
					sql.append(" FROM ");
					sql.append(" 	zy_equipment_change ec ");
					sql.append(" LEFT JOIN t_s_base_user bu ON ec.create_by = bu.username ");
					sql.append(" LEFT JOIN t_s_user_org uo ON bu.id = uo.user_id ");
					sql.append(" LEFT JOIN t_s_depart dp ON uo.org_id = dp.id ");
					sql.append(" LEFT JOIN t_s_type tp ON tp.typecode = ec.change_type ");
					sql.append(" LEFT JOIN t_s_typegroup tg ON tg.id = tp.typegroupid AND tg.typegroupcode = '").append(StaticValue.DIC_EQ_CHANGE_TYPE).append("' ");
					sql.append(" LEFT JOIN t_s_type tp1 ON tp1.typecode = ec.req_reason_type ");
					sql.append(" LEFT JOIN t_s_typegroup tg1 ON tg1.id = tp1.typegroupid AND tg1.typegroupcode = '").append(StaticValue.DIC_REQ_REASON).append("' ");
					sql.append(" LEFT JOIN t_s_type tp2 ON tp2.typecode = ec.approval_state ");
					sql.append(" LEFT JOIN t_s_typegroup tg2 ON tg2.id = tp2.typegroupid AND tg2.typegroupcode = '").append(StaticValue.DIC_EQ_CHANGE_REQ_STATE).append("' ");
					sql.append(" LEFT JOIN zy_cinema cm ON cm.id = ec.cinema_id ");
					sql.append(" WHERE ");
					sql.append(" 	dp.org_code LIKE '").append(depart.getOrgCode()).append("%' ");
					sql.append(" AND dp.logic_delete = 0 ");
					mapList = systemService.findForJdbc(sql.toString());
				}else{
					//如果 当前所属机构为 null （有可能登录时没有set进去。或者根本没配置），那么只查询自己的。（这种可能性极低）
					StringBuffer sql = new StringBuffer();
					sql.append(" SELECT ");
					sql.append(" 	DISTINCT ec.id, ec.change_id AS changeId, DATE_FORMAT(ec.create_date,'%Y-%m-%d') AS createDate, tp.typename AS changeTypeVal, ");
					sql.append("	ec.create_name AS createName, IFNULL(ec.plan_id,'无') AS planId, ec.equipment_spare_sn, cm.name AS cienmaNameVal, tp1.typename AS reasonTypeVal, ");
					sql.append("	ec.req_other_reason ,ec.approval_state, tp2.typename AS approvalStateVal, ec.approval_remark AS approvalRemark ");
					sql.append(" FROM ");
					sql.append(" 	zy_equipment_change ec ");
					sql.append(" LEFT JOIN t_s_type tp ON tp.typecode = ec.change_type ");
					sql.append(" LEFT JOIN t_s_typegroup tg ON tg.id = tp.typegroupid AND tg.typegroupcode = '").append(StaticValue.DIC_EQ_CHANGE_TYPE).append("' ");
					sql.append(" LEFT JOIN t_s_type tp1 ON tp1.typecode = ec.req_reason_type ");
					sql.append(" LEFT JOIN t_s_typegroup tg1 ON tg1.id = tp1.typegroupid AND tg1.typegroupcode = '").append(StaticValue.DIC_REQ_REASON).append("' ");
					sql.append(" LEFT JOIN t_s_type tp2 ON tp2.typecode = ec.approval_state ");
					sql.append(" LEFT JOIN t_s_typegroup tg2 ON tg2.id = tp2.typegroupid AND tg2.typegroupcode = '").append(StaticValue.DIC_EQ_CHANGE_REQ_STATE).append("' ");
					sql.append(" LEFT JOIN zy_cinema cm ON cm.id = ec.cinema_id ");
					sql.append(" WHERE ");
					sql.append(" 	ec.create_by = '").append(user.getUserName()).append("' ");
					mapList = systemService.findForJdbc(sql.toString());
				}
				break;//一定要break
			}else{
				//如果不是第三方负责人 ，只查询自己的申请
				StringBuffer sql = new StringBuffer();
				sql.append(" SELECT ");
				sql.append(" 	DISTINCT ec.id, ec.change_id AS changeId, DATE_FORMAT(ec.create_date,'%Y-%m-%d') AS createDate, tp.typename AS changeTypeVal, ");
				sql.append("	ec.create_name AS createName, IFNULL(ec.plan_id,'无') AS planId, ec.equipment_spare_sn, cm.name AS cienmaNameVal, tp1.typename AS reasonTypeVal, ");
				sql.append("	ec.req_other_reason ,ec.approval_state , tp2.typename AS approvalStateVal, ec.approval_remark AS approvalRemark ");
				sql.append(" FROM ");
				sql.append(" 	zy_equipment_change ec ");
				sql.append(" LEFT JOIN t_s_type tp ON tp.typecode = ec.change_type ");
				sql.append(" LEFT JOIN t_s_typegroup tg ON tg.id = tp.typegroupid AND tg.typegroupcode = '").append(StaticValue.DIC_EQ_CHANGE_TYPE).append("' ");
				sql.append(" LEFT JOIN t_s_type tp1 ON tp1.typecode = ec.req_reason_type ");
				sql.append(" LEFT JOIN t_s_typegroup tg1 ON tg1.id = tp1.typegroupid AND tg1.typegroupcode = '").append(StaticValue.DIC_REQ_REASON).append("' ");
				sql.append(" LEFT JOIN t_s_type tp2 ON tp2.typecode = ec.approval_state ");
				sql.append(" LEFT JOIN t_s_typegroup tg2 ON tg2.id = tp2.typegroupid AND tg2.typegroupcode = '").append(StaticValue.DIC_EQ_CHANGE_REQ_STATE).append("' ");
				sql.append(" LEFT JOIN zy_cinema cm ON cm.id = ec.cinema_id ");
				sql.append(" WHERE ");
				sql.append(" 	ec.create_by = '").append(user.getUserName()).append("' ");
				mapList = systemService.findForJdbc(sql.toString());
				break;//一定要break
			}
		}
		return mapList;
	}

    @Override
    public void queryIpInfoByPlanId(HttpServletRequest req, AjaxJson j) {
        String planId = req.getParameter("planId");
		if(StringUtil.isNotEmpty(planId)){
			ZyInspectionPlanEntity zyIp = super.findUniqueByProperty(ZyInspectionPlanEntity.class, "planId", planId);
			if(null != zyIp && null != zyIp.getEquipmentSpare()){
				Map<String, Object> rsMap = new HashMap<String, Object>();
				rsMap.put("esSn",zyIp.getEquipmentSpare().getSn());
				if(null != zyIp.getEquipmentSpare().getZyCinema()){
					rsMap.put("cmId",zyIp.getEquipmentSpare().getZyCinema().getId());
					rsMap.put("cmName",zyIp.getEquipmentSpare().getZyCinema().getName());
				}
				j.setAttributes(rsMap);
			}else{
				j.setSuccess(false);
				j.setMsg("没有查询到结果");
			}
		}else{
			j.setMsg("巡检计划ID为空");
			j.setSuccess(false);
		}
    }


}